package io.renren.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.sys.dao.DictDao;
import io.renren.modules.sys.entity.DictEntity;
import io.renren.modules.sys.service.DictService;


/**
 * @author Amadeus
 */
@Service("dictService")
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {

    @Autowired
    private DictDao dictDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DictEntity> page = this.page(
                new Query<DictEntity>().getPage(params),
                new QueryWrapper<DictEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDict(DictEntity dict) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        dict.setCreateBy(user.getUsername());
        this.save(dict);
    }

    @Override
    public void saveOrUpdateDict(DictEntity dict) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        dict.setUpdateBy(user.getUsername());
        this.saveOrUpdate(dict);
    }

    @Override
    public PageUtils getDictList(Map<String, Object> params) {
        String key = (String) params.get("key");
        IPage<DictEntity> page = this.page(
                new Query<DictEntity>().getPage(params),
                Wrappers.<DictEntity>lambdaQuery()
                        .like(StrUtil.isNotBlank(key), DictEntity::getDictName, key)
                        .or().like(StrUtil.isNotBlank(key), DictEntity::getCreateBy, key)
                        .or().like(StrUtil.isNotBlank(key), DictEntity::getUpdateBy, key)
                        .or().like(StrUtil.isNotBlank(key), DictEntity::getDescription, key)
                        .or().like(StrUtil.isNotBlank(key), DictEntity::getDictCode, key)
        );

        return new PageUtils(page);
    }

    @Override
    public String queryDictTextByKey(String code, String key) {
        return dictDao.queryDictTextByKey(code, key);
    }

    @Override
    public String queryTableDictTextByKey(String code, String text, String table, String key) {
        return dictDao.queryTableDictTextByKey(code, text, table, key);
    }

}